import TIM from 'tim-wx-sdk';
import TIMUploadPlugin from 'tim-upload-plugin';

let from;
let to;
let rid;

let app = getApp();

let options = {
  SDKAppID: app.globalData.SDKAppID // SDKAppID
};

// 创建 SDK 实例，`TIM.create()`方法对于同一个 `SDKAppID` 只会返回同一份实例
let tim = TIM.create(options); // SDK 实例通常用 tim 表示

let onMessageReceived = function (event) {
  console.log(event);

  let page = getCurrentPages()[getCurrentPages().length - 1];
  let temp = page.data.messageList;
  let msg = event.data[0];
  //如果是文本消息，需要解析后再加入到messageList中
  // if (msg.type === "TIMTextElem") {
  //   page.parseTexts([msg]);
  // }
  temp.push(msg);
  page.setData({
    messageList: temp,
    toView: 'msg-' + (temp.length - 1)
  });
  //如果是结束语
  if (event.data[0].payload.text === '--结束咨询--') {
    wx.request({
      url: app.globalData.prefix + '/record/getConsultRecord/' + rid,
      success: (res) => {
        //第一步，停止计时器
        app.timerStop();
        //第二步，更新map
        let temp2 = page.data.map;
        temp2[rid] = res.data.data;
        let temp3 = page.data.commentMap;
        temp3[rid] = {};
        page.setData({
          map: temp2,
          commentMap: temp3
        });
        //第三步，更改缓存信息
        wx.removeStorageSync('ongoingId');
        wx.removeStorageSync('isWaiting');
        wx.removeStorageSync('rid');
        //第四步，设置isConsulting为false，不再允许咨询
        page.setData({
          isConsulting: false
        })
      }
    })
  }
  //如果是图片
  if (event.data[0].type === 'TIMImageElem') {
    let url = event.data[0].payload.imageInfoArray[0].imageUrl;
    let temp = page.data.imageList;
    temp.push(url);
    page.setData({
      imageList: temp
    })
  }
};

//网上cv的
function dateFormat(fmt, date) {
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "H+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "S+": date.getSeconds().toString() // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
    };
  };
  return fmt;
}

//处理发送语音
const recorderManager = wx.getRecorderManager()
recorderManager.onStart(() => {
  wx.showLoading({
    title: '录音中',
  })
  console.log('recorder start')
})
recorderManager.onStop((res) => {
  console.log('recorder stop', res)
  wx.hideLoading();
  wx.showLoading({
    title: '发送中',
  })
  const message = tim.createAudioMessage({
    to: '' + to,
    conversationType: TIM.TYPES.CONV_C2C,
    payload: {
      file: res
    },
    cloudCustomData: rid
  });
  let promise = tim.sendMessage(message);
  promise.then(function (imResponse) {
    // 发送成功
    console.log(imResponse);
    // 消息上屏
    let pages = getCurrentPages();
    let page = pages[pages.length - 1];
    let temp = page.data.messageList;
    temp.push(imResponse.data.message);
    page.setData({
      messageList: temp,
      toView: 'msg-' + (temp.length - 1)
    });
    wx.hideLoading();
  }).catch(function (imError) {
    // 发送失败
    console.warn('sendMessage error:', imError);
  });
})

//语音播放器
const innerAudioContext = wx.createInnerAudioContext()
innerAudioContext.onPlay(() => {
  console.log('开始播放')
})

Page({

  /**
   * 页面的初始数据
   */
  data: {

    //如果是false，表明访客只是来看聊天记录的，此时不具备发送消息和结束咨询的能力
    isConsulting: false,

    messageList: [],

    text: '',

    nextReqMessageID: '',

    isCompleted: true,

    consultant: {},
    visitor: {},

    second: '00',
    minute: '00',
    hour: '00',

    toView: '',

    map: new Map(),

    commentMap: new Map(),

    imageList: [],

    timerId: 0,

    textMode: true

  },

  browseHistory: function (e) {
    let json = e.currentTarget.dataset.json;
    let datetime = e.currentTarget.dataset.datetime;
    wx.setStorageSync("json", json);
    wx.navigateTo({
      url: '../consultantRecord/consultantRecord?datetime=' + datetime + '&from=' + from + '&to=' + to
    });
  },

  //输入框
  handleInput: function (e) {
    this.setData({
      text: e.detail.value
    })
  },

  //刷新消息列表，刷新后只显示最近的15条记录
  refreshMessageList: function () {

    //假设现在是和某个人在聊天，那么对方的id肯定是知道的，于是可以拼接出会话的id
    let conversationId = 'C2C' + to;

    //获取这个会话的聊天记录
    //第一次拉取最多拉15条
    let promise = tim.getMessageList({
      conversationID: conversationId,
      count: 15
    });

    var that = this;

    promise.then(function (imResponse) {
      const messageList = imResponse.data.messageList; // 消息列表
      that.checkAndUpdateMap(messageList);
      that.checkAndUpdateImageList(messageList);
      // that.parseTexts(messageList);
      console.log(messageList);
      const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉
      const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息
      that.setData({
        messageList,
        nextReqMessageID,
        isCompleted,
        toView: 'msg-' + (messageList.length - 1),
      })
    });

  },

  //发送文本消息，新消息需要即时更新到页面上
  handleSend: function (e) {
    if (!this.data.isConsulting) {
      wx.showToast({
        title: '无法进行该操作',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (this.data.text === '') {
      wx.showToast({
        title: '请输入你要发送的消息',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (this.data.text.length >= 200) {
      wx.showToast({
        title: '消息内容过长',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    wx.showLoading({
      title: '发送中',
    })
    let message = tim.createTextMessage({
      //接收方的userId
      to: '' + to,
      //端到端
      conversationType: TIM.TYPES.CONV_C2C,
      //消息内容
      payload: {
        text: this.data.text
      },
      cloudCustomData: rid
    });
    this.setData({
      text: ''
    })
    var that = this;
    let promise = tim.sendMessage(message);
    promise.then(function (imResponse) {
      // 发送成功
      console.log(imResponse, 111);
      // 需要把text改成方便展示的形式再放到messageList里
      // that.parseTexts([imResponse.data.message]);
      // 把新发的消息加到messageList中
      let temp = that.data.messageList;
      temp.push(imResponse.data.message);
      that.setData({
        messageList: temp,
        toView: 'msg-' + (that.data.messageList.length - 1)
      });
      wx.hideLoading();
    }).catch(function (imError) {
      // 发送失败
      console.warn('sendMessage error:', imError);
    });
  },

  //滑动至顶部时获取历史消息
  handleScroll: function (e) {

    if (this.data.isCompleted) {
      wx.showToast({
        title: '已无更多的聊天记录',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    let conversationId = 'C2C' + to;
    var that = this;
    let promise = tim.getMessageList({
      conversationID: conversationId,
      nextReqMessageID: that.data.nextReqMessageID,
      count: 15
    });
    wx.showLoading({
      title: '加载中',
    })
    promise.then(function (imResponse) {
      const messageList = imResponse.data.messageList;
      that.checkAndUpdateMap(messageList);
      that.checkAndUpdateImageList(messageList);
      // that.parseTexts(messageList);
      const nextReqMessageID = imResponse.data.nextReqMessageID;
      const isCompleted = imResponse.data.isCompleted;
      //注意新的消息是要前插到messageList里的
      let temp = messageList.concat(that.data.messageList);
      that.setData({
        messageList: temp,
        nextReqMessageID,
        isCompleted,
        toView: 'msg-' + (messageList.length),
      })
      wx.hideLoading();
    });
  },

  //发送图片消息
  handleCommitPicture: function (e) {
    if (!this.data.isConsulting) {
      wx.showToast({
        title: '无法进行该操作',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    // 小程序端发送图片
    // 1. 选择图片
    wx.chooseImage({
      sourceType: ['album'], // 从相册选择
      count: 1, // 只选一张，目前 SDK 不支持一次发送多张图片
      success: function (res) {
        wx.showLoading({
          title: '发送中',
        })
        // 2. 创建消息实例，接口返回的实例可以上屏
        let message = tim.createImageMessage({
          to: '' + to,
          conversationType: TIM.TYPES.CONV_C2C,
          payload: {
            file: res
          },
          cloudCustomData: rid,
          onProgress: function (event) {
            console.log('file uploading:', event)
          }
        });
        // 3. 发送图片
        let promise = tim.sendMessage(message);
        promise.then(function (imResponse) {
          // 发送成功
          console.log(imResponse);
          let p = getCurrentPages()[getCurrentPages().length - 1];
          // 把新发的消息加到messageList中
          let temp = p.data.messageList;
          temp.push(imResponse.data.message);
          // 更新imageList
          let temp2 = p.data.imageList;
          temp2.push(imResponse.data.message.payload.imageInfoArray[0].imageUrl);
          p.setData({
            messageList: temp,
            imageList: temp2,
            toView: 'msg-' + (p.data.messageList.length - 1)
          });
          wx.hideLoading();
        }).catch(function (imError) {
          // 发送失败
          console.warn('sendMessage error:', imError);
        });
      }
    })
  },

  tick: function (e) {
    let conversationId = 'C2C' + to;
    let promise = tim.setMessageRead({
      conversationID: conversationId
    });
    promise.then(function (imResponse) {
      // 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
    }).catch(function (imError) {
      // 已读上报失败
      console.warn('setMessageRead error:', imError);
    });
  },

  onLoad: function (options) {

    tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);

    from = wx.getStorageSync('userId');
    to = options.cid;
    rid = options.rid;
    if (rid === null || rid === undefined || rid === '') {
      rid = wx.getStorageSync('rid');
    }
    let ongongId = wx.getStorageSync('ongoingId');

    //条件：当前进行中的咨询师和当前查看的咨询师是同一人
    if (ongongId == to) {
      this.setData({
        isConsulting: true
      })
    }

    //开始计时
    if (!app.globalData.timerOn && this.data.isConsulting) {
      app.timerStart();
    }
    setInterval(() => {
      //每秒读取一次app中的时间
      this.setData({
        second: app.globalData.second,
        minute: app.globalData.minute,
        hour: app.globalData.hour,
      })
    }, 1000);

    //咨询师
    wx.request({
      url: app.globalData.prefix + '/consultant/getConsultantById/' + to,
      success: (res) => {
        this.setData({
          consultant: res.data.data
        })
      }
    });

    //访客
    wx.request({
      url: app.globalData.prefix + '/visitor/getVisitorById/' + from,
      success: (res) => {
        this.setData({
          visitor: res.data.data
        })
      }
    })

    this.refreshMessageList();

  },

  onShow: function () {

    //开启一个计时器，每秒都将所有消息设置为已读
    let id = setInterval(this.tick, 1000);
    this.setData({
      timerId: id
    })

    //判断缓存中有没有这个key
    let ids = wx.getStorageSync('selectedIds');
    console.log(ids);

    //如果有，说明访客刚刚选择了一些咨询记录想要发送给当前咨询师
    if (!(ids === null || ids === undefined || ids === '')) {
      wx.showLoading({
        title: '发送中',
      })
      wx.removeStorageSync('selectedIds');
      //对于每条咨询记录，我们都把涉及到的所有消息打包成一个消息发送给当前咨询师
      for (let idx in ids) {
        let id = ids[idx];
        console.log("id", id);

        wx.request({
          url: app.globalData.prefix + '/record/getConsultRecord/' + id,
          success: (res) => {
            console.log("recordById", res);

            //先获取到对应的咨询记录
            let record = res.data.data;
            //双方的id
            let visitorId = wx.getStorageSync('userId');
            let consultantId = record.consultant.userInfo.userId;
            //时间范围
            let startTimestamp = new Date(record.recordInfo.datetime.replace(/-/g, "/")).getTime();
            let endTimestamp = startTimestamp + (record.recordInfo.duration + 1) * 60 * 1000;
            // let startTimestamp = new Date("2022/3/1 00:00:00").getTime();
            // let endTimestamp = new Date("2022/4/3 23:59:59").getTime();
            startTimestamp /= 1000;
            endTimestamp /= 1000;
            //请求得到消息列表
            wx.request({
              url: app.globalData.prefix + '/record/getMessage',
              method: "POST",
              data: {
                "From_Account": '' + visitorId,
                "To_Account": '' + consultantId,
                "MaxCnt": 100,
                "MinTime": startTimestamp,
                "MaxTime": endTimestamp
              },
              success: (res) => {
                console.log("g", res);

                //消息列表
                let history = [];
                for (let i = 0; i < res.data.data.length; i++) {
                  let temp = JSON.parse(res.data.data[i]).MsgList;
                  history = temp.concat(history);
                }
                console.log(history);
                //每个消息都包含了很多内容，这里做一个精简
                let temp = [];
                for (let i = 0; i < history.length; i++) {
                  let msg = history[i];
                  //只支持转发文字消息
                  if (msg.MsgBody[0].MsgType === 'TIMTextElem') {
                    //发送方是用户
                    if (msg.From_Account == from) {
                      temp.push({
                        from: msg.MsgBody[0].MsgContent.Text,
                        to: '',
                        datetime: dateFormat("YYYY-mm-dd HH:MM:SS", new Date(msg.MsgTimeStamp * 1000))
                      });
                    } else if (msg.From_Account == to) {
                      temp.push({
                        from: '',
                        to: msg.MsgBody[0].MsgContent.Text,
                        datetime: dateFormat("YYYY-mm-dd HH:MM:SS", new Date(msg.MsgTimeStamp * 1000))
                      });
                    }
                  }
                  //图片用占位符 
                  else if (msg.MsgBody[0].MsgType === 'TIMImageElem') {
                    //发送方是用户
                    if (msg.From_Account == from) {
                      temp.push({
                        from: '[图片]',
                        to: '',
                        datetime: dateFormat("YYYY-mm-dd HH:MM:SS", new Date(msg.MsgTimeStamp * 1000))
                      });
                    } else if (msg.From_Account == to) {
                      temp.push({
                        from: '',
                        to: '[图片]',
                        datetime: dateFormat("YYYY-mm-dd HH:MM:SS", new Date(msg.MsgTimeStamp * 1000))
                      });
                    }
                  }
                  //转发的消息记录也用占位符 
                  else if (msg.MsgBody[0].MsgType === 'TIMCustomElem') {
                    //发送方是用户
                    if (msg.From_Account == from) {
                      temp.push({
                        from: '[消息记录]',
                        to: '',
                        datetime: dateFormat("YYYY-mm-dd HH:MM:SS", new Date(msg.MsgTimeStamp * 1000))
                      });
                    } else if (msg.From_Account == to) {
                      temp.push({
                        from: '',
                        to: '[消息记录]',
                        datetime: dateFormat("YYYY-mm-dd HH:MM:SS", new Date(msg.MsgTimeStamp * 1000))
                      });
                    }
                  }
                  //语音消息也用占位符 
                  else if (msg.MsgBody[0].MsgType === 'TIMSoundElem') {
                    //发送方是用户
                    if (msg.From_Account == from) {
                      temp.push({
                        from: '[语音消息]',
                        to: '',
                        datetime: dateFormat("YYYY-mm-dd HH:MM:SS", new Date(msg.MsgTimeStamp * 1000))
                      });
                    } else if (msg.From_Account == to) {
                      temp.push({
                        from: '',
                        to: '[语音消息]',
                        datetime: dateFormat("YYYY-mm-dd HH:MM:SS", new Date(msg.MsgTimeStamp * 1000))
                      });
                    }
                  }
                }
                //把temp转为json，然后发给对方，注意得是createCustomMessage
                let json = JSON.stringify(temp);
                let message = tim.createCustomMessage({
                  to: '' + consultantId,
                  conversationType: TIM.TYPES.CONV_C2C,
                  payload: {
                    data: json,
                    description: "forward",
                    extension: record.recordInfo.datetime
                  },
                  cloudCustomData: rid,
                });
                let that = this;
                let promise = tim.sendMessage(message);
                promise.then(function (imResponse) {
                  console.log(imResponse);
                  let temp = that.data.messageList;
                  temp.push(imResponse.data.message);
                  that.setData({
                    messageList: temp,
                    toView: 'msg-' + (temp.length - 1)
                  });
                  wx.hideLoading();
                }).catch(function (imError) {
                  console.warn('sendMessage error:', imError);
                });
              }
            })

          }
        })
      }
    }

  },

  onHide: function () {
    //停止计时器
    clearInterval(this.data.timerId);
  },

  goChooseHistory: function (e) {
    if (!this.data.isConsulting) {
      wx.showToast({
        title: '无法进行该操作',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    wx.navigateTo({
      url: '../chooseRecord/chooseRecord',
    })
  },

  handleEnd: function () {
    if (!this.data.isConsulting) {
      wx.showToast({
        title: '无法进行该操作',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认要结束咨询吗',
      success(res) {
        if (res.confirm) {
          wx.showToast({
            title: '咨询已结束',
            icon: 'success',
            duration: 2000
          });
          wx.request({
            url: app.globalData.prefix + '/record/getConsultRecord/' + rid,
            success: (res) => {
              //计算总时长
              let startTime = new Date(res.data.data.recordInfo.datetime.replace(/-/g, "/")).getTime();
              let endTime = new Date().getTime();
              let duration = Math.ceil((endTime - startTime) / 1000 / 60);
              //更新map
              let temp = that.data.map;
              temp[rid] = res.data.data;
              let temp2 = that.data.commentMap;
              temp2[rid] = {};
              that.setData({
                map: temp,
                commentMap: temp2
              });
              var that2 = that;
              //停止咨询
              wx.request({
                url: app.globalData.prefix + '/visitor/endConsult',
                method: "POST",
                data: {
                  consultRecordId: rid,
                  duration: duration
                },
                success: (res) => {
                  console.log(res);
                  //第一步，停止计时器
                  app.timerStop();
                  //第二步，发送一条代表结束的消息
                  let message = tim.createTextMessage({
                    to: '' + to,
                    conversationType: TIM.TYPES.CONV_C2C,
                    payload: {
                      text: '--结束咨询--'
                    },
                    cloudCustomData: rid,
                  });
                  let promise = tim.sendMessage(message);
                  promise.then(function (imResponse) {
                    console.log(imResponse);
                    //第三步，把新消息更新到界面上
                    let temp = that2.data.messageList;
                    temp.push(imResponse.data.message);
                    that2.setData({
                      messageList: temp,
                      toView: 'msg-' + (temp.length - 1)
                    });
                  }).catch(function (imError) {
                    console.warn('sendMessage error:', imError);
                  });
                  //第四步，更改缓存信息
                  wx.removeStorageSync('ongoingId');
                  wx.removeStorageSync('isWaiting');
                  wx.removeStorageSync('rid');
                  //第五步，设置isConsulting为false，不再允许咨询
                  that.setData({
                    isConsulting: false
                  })
                }
              })
            }
          })
        }
      }
    })
  },

  checkAndUpdateMap: function (messageList) {
    //把所有涉及的咨询记录记录下来
    for (let i = 0; i < messageList.length; i++) {
      if (messageList[i].payload.text === '--结束咨询--') {
        let rid = messageList[i].cloudCustomData;
        if (rid === '') {
          continue;
        }
        wx.request({
          url: app.globalData.prefix + '/record/getConsultRecord/' + rid,
          success: (res) => {
            let temp = this.data.map;
            temp[rid] = res.data.data;
            let temp2 = this.data.commentMap;
            temp2[rid] = {};
            this.setData({
              map: temp,
              commentMap: temp2
            })
          }
        })
      }
    }
  },

  //更新图片列表
  checkAndUpdateImageList: function (messageList) {
    for (let i = messageList.length - 1; i >= 0; i--) {
      if (messageList[i].type === 'TIMImageElem') {
        let url = messageList[i].payload.imageInfoArray[0].imageUrl;
        let temp = this.data.imageList;
        temp.unshift(url);
        this.setData({
          imageList: temp
        })
      }
    }
  },

  handleComment: function (e) {
    let rid_this = e.currentTarget.dataset.rid;
    if (this.data.commentMap[rid_this].grade === undefined || this.data.commentMap[rid_this].grade === null) {
      wx.showToast({
        title: '必须进行评分',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    let grade = this.data.commentMap[rid_this].grade + 1;
    let comment = this.data.commentMap[rid_this].comment;
    if (comment === undefined || comment === null || comment === '') {
      comment = '用户没有进行文字评价~';
    }
    var that = this;
    wx.request({
      url: app.globalData.prefix + '/visitor/commentConsult',
      method: "POST",
      data: {
        consultRecordId: rid_this,
        fromGrade: grade,
        fromComment: comment
      },
      success: (res) => {
        wx.showToast({
          title: '评价成功',
          icon: 'success',
          duration: 2000
        })
        let temp = that.data.map;
        temp[rid_this].recordInfo.fromGrade = grade;
        temp[rid_this].recordInfo.fromComment = comment;
        that.setData({
          map: temp
        })

      }
    })

  },

  handleCommentInput: function (e) {
    let rid_this = e.currentTarget.dataset.rid;
    let temp = this.data.commentMap;
    temp[rid_this].comment = e.detail.value;
    this.setData({
      commentMap: temp
    })
    console.log(this.data.commentMap);
  },

  handleStar: function (e) {
    let rid_this = e.currentTarget.dataset.rid;
    let idx = e.currentTarget.dataset.idx;
    let temp = this.data.commentMap;
    temp[rid_this].grade = idx;
    this.setData({
      commentMap: temp
    })
    console.log(this.data.commentMap);
  },

  onUnload: function () {
    tim.off(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
  },

  handleSelectImage: function (e) {
    wx.previewImage({
      urls: this.data.imageList,
      current: e.currentTarget.dataset.current
    })
  },

  startRecorder: function (e) {
    recorderManager.start();
  },

  stopRecorder: function (e) {
    recorderManager.stop();
  },

  startVoice: function (e) {
    let url = e.currentTarget.dataset.url;
    innerAudioContext.src = url;
    innerAudioContext.play();
  },

  //对文本进行解析
  // parseTexts: function (messageList) {
  //   for (let i = messageList.length - 1; i >= 0; i--) {
  //     if (messageList[i].type === 'TIMTextElem') {
  //       let content = parseText(messageList[i].payload.text);
  //       let res = '';
  //       for (let i = 0; i < content.length; i++) {
  //         let obj = content[i];
  //         if (obj["name"] === 'text') {
  //           res = res + obj["text"];
  //         } else if (obj["name"] === 'img') {
  //           res = res + "<img src='" + obj["src"] + "' style='width:25px;height:25px;box-sizing:border-box;margin-top：30px';display:flex;></img>";
  //         }
  //       }
  //       messageList[i].payload.text = res;
  //     }
  //   }
  // },

  changeMode: function () {
    if (!this.data.isConsulting) {
      wx.showToast({
        title: '无法进行该操作',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    this.setData({
      textMode: !this.data.textMode
    })
  },



})